package cn.edu.henu.team.ui;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.ninegrid.ImageInfo;

import java.io.File;
import java.util.ArrayList;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.datatype.BmobRelation;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.UploadFileListener;
import cn.edu.henu.team.R;
import cn.edu.henu.team.bean._User;
import cn.edu.henu.team.bean.collection;
import cn.edu.henu.team.utils.myImageLoader;

public class AddCollectionActivity extends AppCompatActivity {

    private _User current_user = BmobUser.getCurrentUser(_User.class);

    private ImageView back;
    private String imagePath = null;
    private ArrayList<ImageItem> imageItems;  //因为布局不熟，目前先是一张图片吧
    private TextView add;
    private ImageView image;
    private EditText name_edittext;
    private EditText intro_edittext;
    private String name;
    private String intro;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_collection);

        findView();
        clickEvents();

    }

    public void findView() {
        back =  findViewById(R.id.back);
        add =  findViewById(R.id.add);
        image =  findViewById(R.id.image);
        name_edittext =  findViewById(R.id.name);
        intro_edittext =  findViewById(R.id.introduction);
    }

    public void clickEvents() {
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                name = name_edittext.getText().toString();
                intro = intro_edittext.getText().toString();
                if (name.equals("") && intro.equals("") && imagePath == null)
                    finish();
                else {
                    createDialog();
                }
            }
        });

        image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //打开相册进行选择
               addImage(1);
            }
        });

        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                name = name_edittext.getText().toString();
                intro = intro_edittext.getText().toString();
                if (name.equals(""))
                    Toast.makeText(getApplicationContext(), "收藏夹标题不能为空哦", Toast.LENGTH_SHORT).show();
                else if (imagePath == null)
                    Toast.makeText(getApplicationContext(), "请上传收藏夹封面图片", Toast.LENGTH_SHORT).show();
                else
                    uploadImage_then_create();//发表帖子
            }
        });
    }


    /**
     * 将图片上传到 Bmob然后创建新收藏夹
     */
    public void uploadImage_then_create() {
        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setCancelable(true);
        progressDialog.setMessage("正在创建中...");
        progressDialog.show();
        final BmobFile file = new BmobFile(new File(imagePath));
        file.uploadblock(new UploadFileListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    // 图片上传成功后创建新收藏夹
                    collection this_collection = new collection();
                    this_collection.setUserOnlyId(current_user.getObjectId());
                    this_collection.setName(name);
                    this_collection.setIntroduction(intro);
                    this_collection.setImage(file);
                    this_collection.setPublicOrNot(true);
                    this_collection.save(new SaveListener<String>() {
                        @Override
                        public void done(String s, BmobException e) {
                            if (e == null) {
                                collection temp = new collection();
                                temp.setObjectId(s);
                                BmobRelation relation = new BmobRelation();
                                relation.add(temp);
                                current_user.setMyCollection(relation);// 添加一对多关联
                                current_user.update(new UpdateListener() {
                                    @Override
                                    public void done(BmobException e) {
                                        if (e == null) {
                                            //Toast.makeText(getApplication(), "关联成功", Toast.LENGTH_SHORT).show();
                                            Toast.makeText(getApplicationContext(), "<"+name+">收藏夹创建成功", Toast.LENGTH_SHORT).show();
                                            progressDialog.dismiss();
                                            Intent i = new Intent();
                                            setResult(0, i);
                                            finish();
                                            overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out);
                                        } else {
                                            //Toast.makeText(getApplication(), "关联失败", Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                });
                                //Toast.makeText(getApplication(), "创建成功", Toast.LENGTH_SHORT).show();
                            } else {
                                //Toast.makeText(getApplication(), "创建失败", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                } else {
                    Toast.makeText(getApplication(), "图片上传失败", Toast.LENGTH_SHORT).show();
                    progressDialog.dismiss();
                }
            }
        });
    }

    public void createDialog() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
        alertDialog.setMessage("内容无法保存，确定离开？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        finish();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                    }
                }).create();
        alertDialog.show();
    }
    /*
     *访问相册上传照片
     */
    private void addImage(Integer imageNum) {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new myImageLoader());
        imagePicker.setMultiMode(false);   //多选
        imagePicker.setSelectLimit(imageNum);    //最多选择X张
        imagePicker.setCrop(true);       //不进行裁剪
        Intent intent = new Intent(AddCollectionActivity.this, ImageGridActivity.class);
        startActivityForResult(intent, 100);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == 100) {
                ArrayList<ImageInfo> imageInfo = new ArrayList<>();
                imageItems = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                String[] filePaths = new String[imageItems.size()];
                filePaths[0] = imageItems.get(0).path;
                imagePath = filePaths[0];
                Log.d("path",imagePath);
                Glide.with(this).load(imagePath).into(image);
            }else {
                Toast.makeText(getApplication(), "没有选择图片呢!", Toast.LENGTH_SHORT).show();
            }
        }
    }
}
